package bs

import scala.xml.NodeSeq

import net.liftweb._
import http._
import util._
import Helpers._

class Carousel(contents: NodeSeq*) extends LiftComponent with Activable {
  override val template: NodeSeq = Templates("templates-hidden" :: "bs" :: "_carousel" :: Nil).get

  override def transformer: (NodeSeq) => NodeSeq = {
    import code.lib.ExtCssSel._
    val id = s"carousel-${(math.random * 100).toInt}"
    val script = s"  $$('#$id').carousel();"
    ".carousel [id]" #> id &
      "li" #> contents.indices.map { index =>
        "li [data-target]" #> s"#$id" &
          "li [data-slide-to]" #> s"$index" &? (_active == index) -> "li [class+]" #> "active"
      } & ".item" #> contents.zipWithIndex.map { case (content, index) =>
      ".item *" #> content &? (_active == index) -> ".item [class+]" #> "active"
    } & ".carousel-control [href]" #> s"#$id" andThen // 此处不理解为什么一定要用andThen
      ".slide *<" #> <script type="text/javascript" data-lift="tail">{script}</script>
  }
}

case class CarouselImage(imageUrl: String, linkUrl: String, title: String, content: String) extends LiftComponent {
  override def transformer: (NodeSeq) => NodeSeq = "a [href]" #> linkUrl &
    "img [src]" #> imageUrl & "h4 *" #> title & "p *" #> content

  val template = Templates("templates-hidden" :: "bs" :: "_carousel_image" :: Nil).get
}

case class ImageCarousel(imgs: CarouselImage*) extends Carousel(imgs.map(_.render): _*)
